package com.plat.api.api.action;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.plat.api.anonation.Token;
import com.plat.api.api.action.common.IndexIVideoResult;
import com.plat.api.api.action.common.IndexType;
import com.plat.api.dao.api.*;
import com.plat.api.entity.api.*;
import com.plat.api.util.RandomUtil;
import com.plat.api.util.StringUtil;
import com.plat.api.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: shish
 * Date: 2020/9/1
 * Time: 22:31
 * Description: 首页---一次性加载完毕首页元素避免因为异步导致异步没有加载完毕
 */
@Service
@Slf4j
public class IndexAction {
    @Autowired
    private PlatVideoDao platVideoDao;
    @Autowired
    private PlatBannerDao platBanneryDao;
    @Autowired
    private PlatCategoryDao platCategoryDao;
    @Autowired
    private PlatPeopleDao platPeopleDao;
    @Autowired
    private PlatLiveAction platLiveAction;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private PlatWechatLiveRoomDao platWechatLiveRoomDao;

    /**
     * 初始化首页
     **/
    public JSONObject initIndex(JSONObject jsonObject) throws Exception {
        JSONObject res = new JSONObject();
        //1、记载轮播图
        Object banner = banner();
        res.put("banner", banner);
        //2、加载分类
        Object category = category();
        res.put("category", category);
        //3、加载推荐人物
        Object people = people(jsonObject);
        res.put("people", people);
        //4、直播通道
//        List<PlatWechatLiveRoomEntity> liveList = getPlatWechatLiveRoom(jsonObject, true);
//        res.put("liveList", liveList);
//        //5、加载初始化推荐视频
//        List<IndexIVideoResult> list = recomVideo(jsonObject);
//        res.put("reComInfo", smartRec(list, liveList));
        //6、加载通知信息
        //7、加载大图内容默认只有两张---包含链接（小程序路由、H5链接）
        //8、加载其他信息

        //9、头条预览
        //10、商品推荐
        //11、底部提示信息：
        //12、广告信息：
        //13、加载推荐人物：
        //14、加载首页tab：
        return res;
    }

    /**
     * 智能推荐首页内容
     **/
    private List<IndexIVideoResult> smartRec(List<IndexIVideoResult> resultList, List<PlatWechatLiveRoomEntity> liveRoom) {
        Integer num = RandomUtil.getNum(0, resultList.size());
        if (liveRoom.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                if (num == i) {
                    resultList.get(i).setType(IndexType.LIVE);
                    resultList.get(i).setObject(liveRoom.get(0));
                }
            }
        }
        return resultList;
    }

    private List<IndexIVideoResult> recomVideo(JSONObject jsonObject) {
        JSONObject body = jsonObject.getJSONObject("body");
        Integer page = body.getInteger("page");
        Integer pageSize = body.getInteger("pageSize");
        LambdaQuery<PlatVideoEntity> query = platVideoDao.getSQLManager().lambdaQuery(PlatVideoEntity.class);
        PageQuery<PlatVideoEntity> list = query.orderBy("is_top desc").andEq("is_recommend", 1).orderBy("is_top desc ").page(page, pageSize);
        List<IndexIVideoResult> lis = new ArrayList<>();
        for (PlatVideoEntity platVideoEntity : list.getList()) {
            platVideoEntity.setPoster(StringUtil.solveString(platVideoEntity.getPoster()));
            platVideoEntity.setImageId(StringUtil.solveString(platVideoEntity.getImageId()));
            platVideoEntity.setPublishTime(DateUtil.format(platVideoEntity.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            IndexIVideoResult indexIVideoResult = new IndexIVideoResult();
            indexIVideoResult.setObject(platVideoEntity);
            indexIVideoResult.setType(IndexType.VIDEO);
            if (platVideoEntity.getVideoInfo() != null) {
                JSONObject jsonObject1 = JSONObject.parseObject(platVideoEntity.getVideoInfo());
                platVideoEntity.setVideoInfo(jsonObject1.getJSONObject("format").toJSONString());
            }
            lis.add(indexIVideoResult);
        }
        return lis;
    }

    private Object people(JSONObject body) {
        JSONObject param = body.getJSONObject("body");
        List<PlatPeopleEntity> list = platPeopleDao.all(param.getInteger("page"), 10);
        List<PlatPeopleEntity> li = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).getMainPhoto();
            list.get(i).setMainPhoto(StringUtil.solveString(list.get(i).getMainPhoto()));
            list.get(i).setAlbumId(StringUtil.solveString(list.get(i).getAlbumId()));
            list.get(i).setWorkAlbumId(StringUtil.solveString(list.get(i).getWorkAlbumId()));
            li.add(list.get(i));
        }
        return li;
    }

    private Object category() throws Exception {
        List<PlatCategoryEntity> list = platCategoryDao.all();

        for (PlatCategoryEntity categoryEntity:list) {
            if (categoryEntity.getXcxUrl()!=null){
                categoryEntity.setXcxUrl(UrlUtil.addVersion(categoryEntity.getXcxUrl()));
            }
        }
        return list;
    }

    private Object banner() throws Exception {
        List<PlatBannerEntity> list = platBanneryDao.all();
        for (PlatBannerEntity bannerEntity:list) {
            if (bannerEntity.getIsH5()==1){
                bannerEntity.setUrl(UrlUtil.addVersion(bannerEntity.getUrl()));
            }
        }
        return list;
    }

    public List<PlatWechatLiveRoomEntity> getPlatWechatLiveRoom(JSONObject jsonObject, boolean isRand) throws WxErrorException {
        String accessToken = wxMaService.getAccessToken();
        JSONObject param = jsonObject.getJSONObject("body");
        Integer page = param.getInteger("page");
        Integer pageSize = param.getInteger("pageSize");
        LambdaQuery<PlatWechatLiveRoomEntity> query = platWechatLiveRoomDao.getSQLManager().lambdaQuery(PlatWechatLiveRoomEntity.class);
        List<PlatWechatLiveRoomEntity> list = null;
        if (isRand) {
            list = query.orderBy(" RAND() ").page(1, 1).getList();
        } else {
            list = query.orderBy("id desc").page(page, pageSize).getList();
        }
        JSONArray res = new JSONArray();
        try {
            JSONObject map = new JSONObject();
            map.put("start", page - 1);
            map.put("limit", pageSize);
            String result = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" + accessToken, map.toJSONString());
            res = JSONObject.parseObject(result).getJSONArray("room_info");
        } catch (Exception e) {
            log.info("[获取房间号码失败]");
        }
        List<PlatWechatLiveRoomEntity> list1 = new ArrayList<>();
        for (PlatWechatLiveRoomEntity entity : list) {
            if (res != null) {
                for (Object obj : res) {
                    JSONObject jsobj = (JSONObject) obj;
                    if (String.valueOf(entity.getRoomId()) != null) {
                        if (entity.getRoomId().equals(jsobj.getLong("roomid"))) {
                            Integer liveStatus = jsobj.getInteger("live_status");
                            String liveStatusName = "直播状态";
                            entity.setLiveStatus(liveStatus);
                            if (liveStatus == 101) {
                                liveStatusName = "直播中";
                            }
                            if (liveStatus == 102) {
                                liveStatusName = "未开始";
                            }
                            if (liveStatus == 103) {
                                liveStatusName = "已结束";
                            }
                            if (liveStatus == 104) {
                                liveStatusName = "禁播";
                            }
                            if (liveStatus == 105) {
                                liveStatusName = "暂停";
                            }
                            if (liveStatus == 106) {
                                liveStatusName = "异常";
                            }
                            if (liveStatus == 107) {
                                liveStatusName = "已过期";
                            }
                            entity.setStart_Time(DateUtil.format(entity.getStartTime(), "yyyy-MM-dd hh:mm:ss"));
                            entity.setEnd_Time(entity.getEndTime());
                            entity.setLiveStatusName(liveStatusName);
                            entity.setLiveStatus(liveStatus);
                            platWechatLiveRoomDao.updateById(entity);
                            if (liveStatus == 101 || liveStatus == 102 || liveStatus == 103 || liveStatus == 105) {
                                list1.add(entity);
                            }
                        }
                    }
                }
            }
        }
        return list1;
    }
}
